package com.ruicar.afs.cloud.apply.pre.loan.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.service.ApplyAdminService;
import com.ruicar.afs.cloud.apply.business.service.ApplySignHistoryService;
import com.ruicar.afs.cloud.apply.business.service.ApplySignRelationService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.condition.LoanAppFormStateCondition;
import com.ruicar.afs.cloud.apply.contract.condition.LoanAppSignPeopleListCondition;
import com.ruicar.afs.cloud.apply.contract.enums.CertTypePictureEnum;
import com.ruicar.afs.cloud.apply.contract.enums.IsMainEnum;
import com.ruicar.afs.cloud.apply.contract.service.*;
import com.ruicar.afs.cloud.apply.pre.app.enums.AppEnum;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.approve.utils.ImageUploadUtil;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyAppFaceCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyAppFormStateCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyAppSignAgreeMentCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.apply.pre.loan.vo.FilterParamsVO;
import com.ruicar.afs.cloud.apply.pre.smallprogram.dto.ChangeBankInfoDTO;
import com.ruicar.afs.cloud.apply.pre.smallprogram.service.ApplySmallProgramService;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyFinancingItemsService;
import com.ruicar.afs.cloud.bizcommon.cfca.dto.CfCaSignatureDto;
import com.ruicar.afs.cloud.bizcommon.cfca.service.CfCaSignatureService;
import com.ruicar.afs.cloud.bizcommon.enums.TemplatePrintType;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormManage;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormSealMapping;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormManageService;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormSealMappingService;
import com.ruicar.afs.cloud.common.core.security.service.AfsUser;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.rules.RuleHelper;
import com.ruicar.afs.cloud.common.rules.constants.RuleRunEnum;
import com.ruicar.afs.cloud.common.rules.dto.RuleRunResult;
import com.ruicar.afs.cloud.image.config.FileProperties;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.enums.AttachmentClassEnum;
import com.ruicar.afs.cloud.image.enums.BusiNodeEnum;
import com.ruicar.afs.cloud.image.mapper.ComAttachmentManagementMapper;
import com.ruicar.afs.cloud.image.service.ComAttaManageService;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.vo.UploadInputVo;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysAddressParam;
import com.ruicar.afs.cloud.parameter.commom.enums.AffiliatedWay;
import com.ruicar.afs.cloud.parameter.commom.enums.CarNature;
import com.ruicar.afs.cloud.parameter.commom.enums.OperateWay;
import com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruicar.afs.cloud.apply.common.utils.ApplyConstants.*;
import static com.ruicar.afs.cloud.parameter.commom.utils.ParamConstants.ADDRESS_LEVEL_ONE;
import static com.ruicar.afs.cloud.parameter.commom.utils.ParamConstants.ADDRESS_LEVEL_TWO;


/**
 * @description: 进件App ServiceImpl
 * @author: mingzhi.li
 * @date: 2020/8/17 21:11
 */
@AllArgsConstructor
@Service
@Slf4j
public class ApplyAppServiceImpl implements ApplyAppService {

    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ComAttaManageService comAttaManageService;
    private final ComAttachmentFileService attachmentFileService;
    private final FileProperties fileProperties;
    private final CfCaSignatureService cfCaSignatureService;
    private final ComAttachmentFileService comAttachmentFileService;
    private final ApplyCustAddressService applyCustAddressService;
    private final TsysAddressParamService service;
    private final ApplySignRelationService applySignRelationService;
    private final ApplySignHistoryService applySignHistoryService;
    private final ComPrintFormSealMappingService comPrintFormSealMappingService;
    private final PreApproveService preApproveService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ApplyAffiliatedUnitService applyAffiliatedUnitService;
    private final ApplyCarDetailsService applyCarDetailsService;
    private final ApplyCustPersonalService custPersonalService;
    private final ApplyCustContactsService applyCustContactsService;
    private final ComPrintFormManageService comPrintFormManageService;
    private final ApplyCarInvoiceService applyCarInvoiceService;
    private final ApplyGpsInfoService applyGpsInfoService;
    private final LoanGpsRuleInfoService loanGpsRuleInfoService;
    private final ApplyCostDetailsService applyCostDetailsService;
    private final ApplyFinancingItemsService financingItemsService;
    private final ApplyAddPriceItemsService applyAddPriceItemsService;
    private final ApplyContractInfoService applyContractInfoService;
    private final ApplyChannelInfoService applyChannelInfoService;
    private final ApplyFinancingItemsService applyFinancingItemsService;
    private final ApplyBankCardService applyBankCardService;
    private final ApplyCustPersonalService applyCustPersonalService;
    private final ApplyCustHistoryService applyCustHistoryService;
    private final ApplyAdminService applyAdminService;
    private final ApplySmallProgramService applySmallProgramService;
    private final ComAttachmentManagementMapper managementMapper;
    private final ImageUploadUtil getTempDir;

    /**
     * 根据客户id获取获取上传附件配置参数
     * @param custId
     * @return
     */
    @Override
    public ComAttachmentManagement getComAttachmentManagement(Long custId) {
        ApplyCustBaseInfo info = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getId, custId));
        ComAttachmentManagement management =null;
        if(PRINCIPAL_BORROWER.equals(info.getCustRole())){
            //客户角色：主借人
            management = comAttaManageService.getOne(Wrappers.<ComAttachmentManagement>query().lambda()
                    .eq(ComAttachmentManagement::getUniqueCode, MAIN_BORROWER_ID_CARD_FRONT)
                    .eq(ComAttachmentManagement::getBusiNode, BusiNodeEnum.ORDER_APPLY.getCode()));
        }else if(COMMON_BORROWER.equals(info.getCustRole())){
            //共借人
            management = comAttaManageService.getOne(Wrappers.<ComAttachmentManagement>query().lambda()
                    .eq(ComAttachmentManagement::getUniqueCode, COM_BORROWER_ID_CARD_FRONT)
                    .eq(ComAttachmentManagement::getBusiNode, BusiNodeEnum.ORDER_APPLY.getCode()));
        }else if(GUARANTOR.equals(info.getCustRole())){
            //担保人
            management = comAttaManageService.getOne(Wrappers.<ComAttachmentManagement>query().lambda()
                    .eq(ComAttachmentManagement::getUniqueCode, GUARANTOR_BORROWER_ID_CARD_FRONT)
                    .eq(ComAttachmentManagement::getBusiNode, BusiNodeEnum.ORDER_APPLY.getCode()));
        }else if(CAR_DEALER.equals(info.getCustRole())){
            //车商
            management = comAttaManageService.getOne(Wrappers.<ComAttachmentManagement>query().lambda()
                    .eq(ComAttachmentManagement::getUniqueCode, CertTypePictureEnum.CONTRACT_INVOICE_ID_CARD_FRONT.getIndex())
                    .eq(ComAttachmentManagement::getBusiNode, BusiNodeEnum.LOAN_APPLY.getCode()));
        }
        return management;
    }

    /**
     * 根据附件人脸识别标，获取配置参数信息
     * @return
     */
    @Override
    public ComAttachmentManagement getUserNameManagement() {
        ComAttachmentManagement management = comAttaManageService.getOne(Wrappers.<ComAttachmentManagement>query().lambda()
                .eq(ComAttachmentManagement::getUniqueCode, LOGIN_FACE_PHOTO));
        return management;
    }

    /**
     * 电子签名
     * @param signatureDto
     * @return
     */
    @Override
    public IResponse electronicSignature(CfCaSignatureDto signatureDto) {
        log.info("根据签约场景获取客户信息开始");
        CfCaSignatureDto dto = setCustInfoDto(signatureDto);
        log.info("签约签字开始===========》》"+dto.getCustName());
        Long[] fileId = dto.getFileId();
        for(int i=0;i<fileId.length;i++){
            ComAttachmentFile attachmentFile = attachmentFileService.getById(fileId[i]);
            if(attachmentFile== null){
                return IResponse.fail("文件id不存在");
            }
            //获取合同关联关系表数据
            ApplySignRelation relation = getRelation(dto,attachmentFile);
            //判断模版是否电子签章
            boolean signFlag = getSignFlag(Boolean.TRUE,attachmentFile,dto);
            if(relation == null){
                log.info("获取单个合同关联数据为空"+dto.getCustName()+attachmentFile.getFileName());
                return IResponse.fail("获取单个合同关联数据为空"+dto.getCustName()+attachmentFile.getFileName());
            }
            if(YES.equals(relation.getStatus())){
                log.info("当前签约角色对应合同已签约，角色名称："+dto.getCustName()+"角色id："+dto.getCustId()+"合同模版code:"+attachmentFile.getAttachmentCode());
                continue;
            }
            log.info("获取签章配置信息数据开始");
            ComPrintFormSealMapping mapping = getSignMapping(relation,attachmentFile);
            if(mapping !=null ){
                //签名
                dto.setKeyword(mapping.getKeyword());
            }else{
                log.info("模版参数不存在。请联系管理员,模版id"+attachmentFile.getAttachmentCode());
                return IResponse.fail("模版参数不存在。请联系管理员");
            }

            byte[] fileByte = attachmentFileService.downloadAttachmentFile(attachmentFile);
            if (fileByte.length > 0) {
                dto.setFileByte(fileByte);
            }else{
                log.info("服务器下载待签名文件失败！"+attachmentFile.getFileName());
                return IResponse.fail("服务器下载待签名文件失败！"+attachmentFile.getFileName());
            }
            log.info("组装附件上传实体类vo开始");
            UploadInputVo vo = getInputVo(attachmentFile);
            String outPath = fileProperties.getTempDir() + File.separator + attachmentFile.getFileName();
            File outFile = FileUtil.touch(outPath);
            byte[] file = new byte[0];
            try {
                file = cfCaSignatureService.getCfCaSignature(dto);
            } catch (Exception e) {
                log.info("合成签名文件失败"+attachmentFile.getFileName());
                e.printStackTrace();
            }
            if(file!=null && file.length>0){

                outFile = FileUtil.writeBytes(file,outPath);
                //附件上传
                ComAttachmentFile comAttachmentFile = comAttachmentFileService.storeFileToOss(outFile, vo);
                log.info("签约历史数据存储数据开始"+dto.getCustName()+attachmentFile.getFileName());
                Boolean saveHistoryFlag =  saveSignHistory(dto,comAttachmentFile,relation);
                if(!saveHistoryFlag){
                    log.info("签约历史表保存失败！！");
                    return IResponse.fail("签约历史表保存失败！！");
                }
                if(signFlag){
                    ComPrintFormManage info = comPrintFormManageService.getOne(Wrappers.<ComPrintFormManage>query().lambda().eq(ComPrintFormManage::getId, attachmentFile.getAttachmentCode()));
                    List<ComPrintFormSealMapping> sealMappingList = getSealMapping(attachmentFile);
                    if(sealMappingList !=null && sealMappingList.size()>0){
                        log.info("客户:"+dto.getCustName()+"模版:"+comAttachmentFile.getAttachmentCode()+"盖章开始！！");
                        ComAttachmentFile att = comPrintFormManageService.generateSealFile(comAttachmentFile);
                        deleteAttachmentFile(att,info);
                        saveSignHistory(dto,att,relation);
                        att.setId(null);
                        att.setIsElectronic(YES);
                        att.setAttachmentCode(info.getAscriptionSubClass());
                        att.setFileSource("com_attachment_management");
                        comAttachmentFileService.save(att);
                        saveSignHistory(dto,att,relation);
                    }else{
                        deleteAttachmentFile(comAttachmentFile,info);
                        comAttachmentFile.setId(null);
                        comAttachmentFile.setIsElectronic(YES);
                        comAttachmentFile.setAttachmentCode(info.getAscriptionSubClass());
                        comAttachmentFile.setFileSource("com_attachment_management");
                        comAttachmentFileService.save(comAttachmentFile);
                        saveSignHistory(dto,comAttachmentFile,relation);
                    }
                }
                log.info("签约关联关系表状态更新"+dto.getCustName()+attachmentFile.getFileName());
                if(relation !=null){
                    log.info("签约关联关系表状态更新开始"+dto.getCustName()+attachmentFile.getFileName());
                    relation.setStatus(YES);
                    applySignRelationService.updateById(relation);
                }
                if(MESSAGE_TYPE_ONE.equals(dto.getSignScene())){
                    //协议签约场景
                    boolean roleSignFlag = getRoleSignFlag(Boolean.TRUE,dto);
                    //全部角色已签约情况更新主表签约状态
                    if(roleSignFlag){
                        ApplyOrderInfo applyOrderInfo = applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda().eq(ApplyOrderInfo::getApplyNo, dto.getApplyNo()));
                        if(applyOrderInfo !=null){
                            applyOrderInfo.setSignFlag(YES);
                            applyOrderInfoService.updateById(applyOrderInfo);
                        }
                    }
                }else if(MESSAGE_TYPE_TWO.equals(dto.getSignScene())){
                    //合同签约场景
                    boolean roleSignFlag = getRoleSignFlag(Boolean.TRUE,dto);
                    //全部角色已签约情况更新主表签约状态
                    if(roleSignFlag){
                        ApplyContractInfo contractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda().eq(ApplyContractInfo::getContractNo, dto.getApplyNo()));
                        if(contractInfo !=null){
                            contractInfo.setSignFlag(YES);
                            applyContractInfoService.updateById(contractInfo);
                        }
                    }
                }
                //删除临时文件
                FileUtil.del(outFile);
            }else{
                log.info("签名失败，失败客户"+dto.getCustName());
                return IResponse.fail("签名失败"+dto.getCustName());
            }
        }
        return IResponse.success(true);
    }

    /**
     * 电子签名（贷后银行卡变更）
     * @param signatureDto
     * @return
     */
    @Override
    public IResponse electronicBankInfo(CfCaSignatureDto signatureDto) {
        log.info("根据签约场景获取客户信息开始");
        ChangeBankInfoDTO info =applySmallProgramService.getBankCardInfo(signatureDto.getCaseNo());
        if(info == null){
            log.info("银行卡信息异常,异常编号"+signatureDto.getCaseNo());
            return IResponse.fail("银行卡信息异常");
        }
        //客户姓名
        CfCaSignatureDto dto = new CfCaSignatureDto();
        dto.setCustName(info.getCustName());
        //证件号码
        dto.setCertNo(info.getCertNo());
        //手机号码
        dto.setTelPhone(info.getPhone());
        //详细地址
        dto.setDetailAddress("");
        //关键字
        dto.setKeyword(info.getKeyWord());
        //签约图片文件流
        dto.setFile(signatureDto.getFile());
        //
        dto.setRotationAngle(signatureDto.getRotationAngle());
        log.info("签约签字开始===========》》"+dto.getCustName());
        ComAttachmentFile attachmentFile =null;
                List<ComAttachmentFile> fileList = applySmallProgramService.getFileList(signatureDto.getCaseNo());
        if(fileList !=null || fileList.size()>0){
            attachmentFile =fileList.get(0);
        }
        if(attachmentFile== null){
            return IResponse.fail("文件id不存在");
        }
        byte[] fileByte = attachmentFileService.downloadAttachmentFile(attachmentFile);
        if (fileByte.length > 0) {
            dto.setFileByte(fileByte);
        }else{
            log.info("服务器下载待签名文件失败！"+attachmentFile.getFileName());
            return IResponse.fail("服务器下载待签名文件失败！"+attachmentFile.getFileName());
        }
        log.info("组装附件上传实体类vo开始");
        UploadInputVo vo = getInputVo(attachmentFile);
        String outPath = fileProperties.getTempDir() + File.separator + attachmentFile.getFileName();
        File outFile = FileUtil.touch(outPath);
        byte[] file = new byte[0];
        try {
            file = cfCaSignatureService.getCfCaSignature(dto);
        } catch (Exception e) {
            log.info("合成签名文件失败"+attachmentFile.getFileName());
            e.printStackTrace();
        }
        ComAttachmentFile comAttachmentFile =null;
        if(file!=null && file.length>0){

            outFile = FileUtil.writeBytes(file,outPath);
            //附件上传
            comAttachmentFile = comAttachmentFileService.storeFileToOss(outFile, vo);
            //删除临时文件
            FileUtil.del(outFile);
        }else{
            log.info("签名失败，失败客户"+dto.getCustName());
            return IResponse.fail("签名失败"+dto.getCustName());
        }
        return IResponse.success(comAttachmentFile);
    }

    /**
     * 判断单个模版是否已经签完
     * @param signFlag
     * @param attachmentFile
     * @return
     */
    public Boolean getSignFlag(Boolean signFlag,ComAttachmentFile attachmentFile,CfCaSignatureDto dto) {
        List<ApplySignRelation> relationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getBusinessNo, attachmentFile.getBusiNo())
                .eq(ApplySignRelation::getTempleId,attachmentFile.getAttachmentCode())
                .ne(ApplySignRelation::getCustId, dto.getCustId()));
        if(relationList !=null && relationList.size()>0){
            for(ApplySignRelation signRelation:relationList){
                if(NO.equals(signRelation.getStatus())){
                    signFlag=false;
                    break;
                }
            }
        }
        return signFlag;
    }

    /**
     * 判断单个角色是否已经签完
     * @param signFlag
     * @param dto
     * @return
     */
    public Boolean getRoleSignFlag(Boolean signFlag,CfCaSignatureDto dto) {
        List<ApplySignRelation> relationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getBusinessNo, dto.getApplyNo())
                .ne(ApplySignRelation::getCustId, dto.getCustId()));
        if(relationList !=null && relationList.size()>0){
            for(ApplySignRelation signRelation:relationList){
                if(NO.equals(signRelation.getStatus())){
                    signFlag=false;
                    break;
                }
            }
        }
        return signFlag;
    }

    /**
     * 根据客户id、模版id获取合同关联关系表数据
     * @param dto
     * @param attachmentFile
     * @return
     */
    public ApplySignRelation getRelation(CfCaSignatureDto dto,ComAttachmentFile attachmentFile){
        ApplySignRelation relation = applySignRelationService.getOne(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getCustId, dto.getCustId())
                .eq(ApplySignRelation::getTempleId,attachmentFile.getAttachmentCode())
                .eq(ApplySignRelation::getBusinessNo,dto.getApplyNo()));
        return relation;
    }

    /**
     * 根据模版id、签章类型、客户角色获取单个模版签名信息
     * @param relation
     * @param attachmentFile
     * @return
     */
    public ComPrintFormSealMapping getSignMapping(ApplySignRelation relation,ComAttachmentFile attachmentFile){
        ComPrintFormSealMapping mapping = comPrintFormSealMappingService.getOne(Wrappers.<ComPrintFormSealMapping>query().lambda()
                .eq(ComPrintFormSealMapping::getTemplateId, attachmentFile.getAttachmentCode())
                .eq(ComPrintFormSealMapping::getTemplateModuleType, "sign")
                .eq(ComPrintFormSealMapping::getCustRole,relation.getCustRole()));
        return mapping;
    }

    /**
     * 根据模版id、签章类型、客户角色获取单个模版签章
     * @param attachmentFile
     * @return
     */
    public List<ComPrintFormSealMapping> getSealMapping(ComAttachmentFile attachmentFile){
        List<ComPrintFormSealMapping> mappingList = comPrintFormSealMappingService.list(Wrappers.<ComPrintFormSealMapping>query().lambda()
                .eq(ComPrintFormSealMapping::getTemplateId, attachmentFile.getAttachmentCode())
                .eq(ComPrintFormSealMapping::getTemplateModuleType, "seal"));
        return mappingList;
    }

    /**
     * 组装附件上传实体类
     * @param attachmentFile
     * @return
     */
    public UploadInputVo getInputVo(ComAttachmentFile attachmentFile){
        UploadInputVo vo = new UploadInputVo();
        vo.setAttachmentId(attachmentFile.getAttachmentCode());
        vo.setBusiNo(attachmentFile.getBusiNo());
        vo.setBelongNo(attachmentFile.getBusiNo());
        vo.setAttachmentName(attachmentFile.getAttachmentName());
        vo.setFileName(attachmentFile.getFileName());
        vo.setFileType(TemplatePrintType.PDF.name());
        vo.setArchiveClass(attachmentFile.getArchiveClass());
        vo.setIsDelete(NO);
        vo.setIsElectronic(YES);
        vo.setFileSource("com_print_form_manage");
        return vo;
    }

    /**
     * 保存签约历史记录
     * @param dto
     * @param comAttachmentFile
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveSignHistory(CfCaSignatureDto dto,ComAttachmentFile comAttachmentFile,ApplySignRelation relation) {
        ApplySignHistory history = new ApplySignHistory();
        //申请编号
        history.setBusinessNo(comAttachmentFile.getBusiNo());
        //客户id
        history.setCustId(dto.getCustId());
        //客户姓名
        history.setCustName(dto.getCustName());
        //文件id
        history.setFileId(comAttachmentFile.getId());
        //文件名称
        history.setFileName(comAttachmentFile.getFileName());
        //模版id
        history.setTempleId(Long.valueOf(comAttachmentFile.getAttachmentCode()));
        //模版名称
        history.setTempleName(comAttachmentFile.getAttachmentName());
        //文件名称
        history.setFileName(comAttachmentFile.getFileName());
        //签约关联关联表
        history.setRelationId(relation.getId());
        applySignHistoryService.save(history);
        return Boolean.TRUE;
    }

    /**
     * app电子签约前删除手工上传附件
     * @param comAttachmentFile
     * @param info
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteAttachmentFile(ComAttachmentFile comAttachmentFile,ComPrintFormManage info) {
        List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                .eq(ComAttachmentFile::getAttachmentCode, info.getAscriptionSubClass())
                .eq(ComAttachmentFile::getBusiNo, comAttachmentFile.getBusiNo())
                .eq(ComAttachmentFile::getFileSource,"com_attachment_management")
                .ne(ComAttachmentFile::getIsElectronic,YES).orderByDesc(ComAttachmentFile::getCreateTime));
        if(attachmentList !=null && attachmentList.size()>0){
            for(ComAttachmentFile file:attachmentList){
                attachmentFileService.removeById(file);
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 获取角色最新签约附件
     * @param condition
     * @return
     */
    @Override
    public List<ComAttachmentFile> getApplyFileList(ApplyAppSignAgreeMentCondition condition) {
        List<ComAttachmentFile> fileList = new ArrayList<>();
        log.info("从合同签约关系表获取签约数据开始=========》》》》");
        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getCustId, condition.getCustId())
                .eq(ApplySignRelation::getBusinessNo,condition.getApplyNo()));
        if(signRelationList !=null && signRelationList.size()>0){
            log.info("签约文件list组装开始");
            for(ApplySignRelation relation :signRelationList){
                List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getAttachmentCode, relation.getTempleId().toString())
                        .eq(ComAttachmentFile::getBusiNo, condition.getApplyNo()).orderByDesc(ComAttachmentFile::getCreateTime));
                if(attachmentList !=null && attachmentList.size()>0){
                    fileList.add(attachmentList.get(0));
                }
            }
        }
        return fileList;
    }

    /**
     * 获取所有进件最新签约附件
     * @param condition
     * @return
     */
    @Override
    public List<ComAttachmentFile> getApplyFileListAll(ApplyAppFormStateCondition condition) {
        List<ComAttachmentFile> fileList = new ArrayList<>();
        log.info("从合同签约关系表获取签约数据开始=========》》》》");
        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getBusinessNo,condition.getApplyNo()));
        if(signRelationList !=null && signRelationList.size()>0){
            log.info("签约文件list组装开始");
            for(ApplySignRelation relation :signRelationList){
                List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getAttachmentCode, relation.getTempleId().toString())
                        .eq(ComAttachmentFile::getBusiNo, condition.getApplyNo()).orderByDesc(ComAttachmentFile::getCreateTime));
                if(attachmentList !=null && attachmentList.size()>0){
                    fileList.add(attachmentList.get(0));
                }
            }
        }
        return fileList;
    }

    /**
     * 进件所有角色是否全部生成合同
     * @param condition
     * @return
     */
    @Override
    public String getApplyFileIsComplete(ApplyAppFormStateCondition condition) {
        String isComplete=YES;
        //查询有多少个角色
        List<ApplyCustBaseInfo> custBaseInfos = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()));
        if(custBaseInfos !=null && custBaseInfos.size()>0){
            for(ApplyCustBaseInfo info :custBaseInfos){
                log.info("从合同签约关系表获取签约数据开始=========》》》》");
                List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                        .eq(ApplySignRelation::getBusinessNo,condition.getApplyNo())
                        .eq(ApplySignRelation::getCustId,info.getId()));
                if(signRelationList ==null || signRelationList.size()==0){
                    isComplete=NO;
                    break;
                }
            }
        }

        return isComplete;
    }

    /**
     * 获取单个角色签约附件
     * @param condition
     * @return
     */
    @Override
    public List<ComAttachmentFile> getLoanFileList(LoanAppSignPeopleListCondition condition) {
        List<ComAttachmentFile> fileList = new ArrayList<>();
        log.info("从合同签约关系表获取签约数据开始=========》》》》");
        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getCustId, condition.getCustId())
                .eq(ApplySignRelation::getBusinessNo,condition.getContractNo()));
        if(signRelationList !=null && signRelationList.size()>0){
            log.info("签约文件list组装开始");
            for(ApplySignRelation relation :signRelationList){
                List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getAttachmentCode, relation.getTempleId().toString())
                        .eq(ComAttachmentFile::getBusiNo, condition.getContractNo()).orderByDesc(ComAttachmentFile::getCreateTime));
                if(attachmentList !=null && attachmentList.size()>0){
                    fileList.add(attachmentList.get(0));
                }
            }
        }
        return fileList;
    }

    /**
     * 获取放款所有签约附件
     * @param condition
     * @return
     */
    @Override
    public List<ComAttachmentFile> getLoanFileListAll(LoanAppFormStateCondition condition) {
        List<ComAttachmentFile> fileList = new ArrayList<>();
        log.info("从合同签约关系表获取签约数据开始=========》》》》");
        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getBusinessNo,condition.getContractNo()));
        if(signRelationList !=null && signRelationList.size()>0){
            log.info("签约文件list组装开始");
            for(ApplySignRelation relation :signRelationList){
                List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getAttachmentCode, relation.getTempleId().toString())
                        .eq(ComAttachmentFile::getBusiNo, condition.getContractNo()).orderByDesc(ComAttachmentFile::getCreateTime));
                if(attachmentList !=null && attachmentList.size()>0){
                    fileList.add(attachmentList.get(0));
                }
            }
        }
        return fileList;
    }

    /**
     * 放款所有角色是否全部生成合同
     * @param condition
     * @return
     */
    @Override
    public String getLoanFileIsComplete(LoanAppFormStateCondition condition) {
        String isComplete=YES;
        //查询有多少个角色
        List<ApplyCustBaseInfo> custBaseInfos = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()));
        if(custBaseInfos !=null && custBaseInfos.size()>0){
            for(ApplyCustBaseInfo info :custBaseInfos){
                log.info("从合同签约关系表获取签约数据开始=========》》》》");
                List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                        .eq(ApplySignRelation::getBusinessNo,condition.getContractNo())
                        .eq(ApplySignRelation::getCustId,info.getId()));
                if(signRelationList ==null || signRelationList.size()==0){
                    isComplete=NO;
                    break;
                }
            }
        }

        return isComplete;
    }

    /**
     * 获取角色签约附件
     * @param condition
     * @return
     */
    @Override
    public List<ComAttachmentFile> getPreFileList(ApplyAppSignAgreeMentCondition condition) {
        List<ComAttachmentFile> fileList = new ArrayList<>();
        log.info("从合同签约关系表获取签约数据开始=========》》》》");
        if(MESSAGE_TYPE_ZERO.equals(condition.getSignScene())){
            //预审批获取签约文件
            List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                    .eq(ApplySignRelation::getCustId, condition.getPreId())
                    .eq(ApplySignRelation::getBusinessNo,condition.getPreId().toString()));
            if(signRelationList !=null && signRelationList.size()>0){
                log.info("签约文件list组装开始");
                for(ApplySignRelation relation :signRelationList){
                    List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                            .eq(ComAttachmentFile::getAttachmentCode, relation.getTempleId().toString())
                            .eq(ComAttachmentFile::getBusiNo, condition.getPreId().toString()).orderByDesc(ComAttachmentFile::getCreateTime));
                    if(attachmentList !=null && attachmentList.size()>0){
                        attachmentList.get(0).setSignStatus(relation.getStatus());
                        fileList.add(attachmentList.get(0));
                    }
                }
            }
        }else{
            //主借人、共借人、担保人获取签约文件（小程序签约征信授权书）
            List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                    .eq(ApplySignRelation::getCustId, condition.getCustId())
                    .eq(ApplySignRelation::getBusinessNo,condition.getApplyNo()));
            if(signRelationList !=null && signRelationList.size()>0){
                log.info("签约文件list组装开始");
                for(ApplySignRelation relation :signRelationList){
                    List<ComAttachmentFile> attachmentList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                            .eq(ComAttachmentFile::getAttachmentCode, relation.getTempleId().toString())
                            .eq(ComAttachmentFile::getBusiNo, condition.getApplyNo()).orderByDesc(ComAttachmentFile::getCreateTime));
                    if(attachmentList !=null && attachmentList.size()>0){
                        attachmentList.get(0).setSignStatus(relation.getStatus());
                        fileList.add(attachmentList.get(0));
                    }
                }
            }
        }
        return fileList;
    }

    /**
     * 组装签约客户签约签名信息
     * @param dto
     * @return
     */
    public CfCaSignatureDto setCustInfoDto(CfCaSignatureDto dto) {
        if(MESSAGE_TYPE_ZERO.equals(dto.getSignScene())){
            PreApproveInfo info = preApproveService.getOne(Wrappers.<PreApproveInfo>query().lambda()
                    .eq(PreApproveInfo::getId, dto.getCustId()));
            log.info("客户信息赋值开始、赋值客户姓名、证件类型、证件号码、手机号码");
            if(info !=null){
                //客户姓名
                dto.setCustName(info.getCustName());
                //证件号码
                dto.setCertNo(info.getCertNo());
                //手机号码
                dto.setTelPhone(info.getTelPhone());
                //详细地址
                dto.setDetailAddress("");
            }else{
                log.info("客户信息不存在");
                return dto;
            }
        }else{
            List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                    .eq(ApplySignRelation::getCustId, dto.getCustId().toString()));
            if(signRelationList !=null && signRelationList.size()>0){
                AfsUser user = SecurityUtils.getUser();
                ApplySignRelation relation = signRelationList.get(0);
                if(WITNESSES.equals(relation.getCustRole())){
                    IResponse vo = applyAdminService.getUserInfoByUsername(user.getUsername());
                    if(CODE_SUCCESS.equals(vo.getCode())){
                        Map map = (Map) vo.getData();
                        //客户姓名
                        dto.setCustName(user.getUserRealName());
                        //证件号码
                        dto.setCertNo((String) map.get("identityNumber"));
                        //手机号码
                        dto.setTelPhone((String) map.get("phone"));
                        //地址信息：暂无
                        dto.setDetailAddress("");
                    }
                }else if(CAR_DEALER.equals(relation.getCustRole())){
                    ApplyCarInvoice applyCarInvoice = applyCarInvoiceService.getOne(Wrappers.<ApplyCarInvoice>query().lambda()
                            .eq(ApplyCarInvoice::getId, dto.getCustId().toString())
                            .eq(ApplyCarInvoice::getInvoiceNature,"personal"));
                    if(applyCarInvoice !=null){
                        //地址信息：暂无
                        dto.setDetailAddress("");
                        //客户姓名
                        dto.setCustName(applyCarInvoice.getSaleName());
                        //证件号码
                        dto.setCertNo(applyCarInvoice.getSaleCertNo());
                        //手机号码
                        dto.setTelPhone(applyCarInvoice.getSalePhone());
                    }
                }else{
                    ApplyCustBaseInfo info = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                            .eq(ApplyCustBaseInfo::getId, dto.getCustId().toString()));
                    log.info("客户信息赋值开始、赋值客户姓名、证件类型、证件号码、手机号码");
                    if(info !=null){
                        //客户姓名
                        dto.setCustName(info.getCustName());
                        //证件号码
                        dto.setCertNo(info.getCertNo());
                        //手机号码
                        dto.setTelPhone(info.getTelPhone());
                        //证件类型
                        dto.setCertType(info.getCustType());
                    }else{
                        log.info("客户信息不存在");
                        return dto;
                    }
                    log.info("详细地址赋值开始、赋值户籍详细地址");
                    ApplyCustAddressDetails address = applyCustAddressService.getOne(Wrappers.<ApplyCustAddressDetails>query().lambda()
                            .eq(ApplyCustAddressDetails::getCustId, dto.getCustId()).eq(ApplyCustAddressDetails::getIsMain, IsMainEnum.isMain.getCode()));
                    if(address !=null){
                        // 省份查询
                        TsysAddressParam param = service.getOne(Wrappers.<TsysAddressParam>query().lambda()
                                .eq(TsysAddressParam::getValue, address.getProvince()).eq(TsysAddressParam::getAddrLevel, ADDRESS_LEVEL_ONE));
                        // 城市查询
                        TsysAddressParam addressParam = service.getOne(Wrappers.<TsysAddressParam>query().lambda()
                                .eq(TsysAddressParam::getValue, address.getCity()).eq(TsysAddressParam::getAddrLevel, ADDRESS_LEVEL_TWO));
                        if(param !=null && addressParam !=null){
                            dto.setDetailAddress(param.getLabel()+addressParam.getLabel()+address.getDetailAddress());
                        }
                    }
                }
            }
            return dto;
        }
        return dto;
    }

    /**
     * 获取进件flag业务类型数据信息
     * @param condition
     * @return
     */
    @Override
    public ApplyAppFormStateCondition getBusinessTypeArea(ApplyAppFormStateCondition condition) {
        ApplyOrderInfo applyOrderInfo = applyOrderInfoService.getOne(Wrappers.<ApplyOrderInfo>query().lambda().eq(ApplyOrderInfo::getApplyNo, condition.getApplyNo()));
        if(applyOrderInfo !=null){
            //是否已录入：是
            condition.setBusinessTypeState(APP_FORM_STATE_ONE);
        }else{
            //是否已录入：否
            condition.setBusinessTypeState(APP_FORM_STATE_ZERO);
        }
        if(!StrUtil.isBlank(applyOrderInfo.getRemarks())){
            //是否已录入：是
            condition.setRemarkState(APP_FORM_STATE_ONE);
        }else{
            //是否已录入：否
            condition.setRemarkState(APP_FORM_STATE_ZERO);
        }
        //业务类型
        condition.setBusinessType(applyOrderInfo.getBusinessType());
        //挂靠方式
        condition.setAffiliatedWay(applyOrderInfo.getAffiliatedWay());
        //车辆属性
        condition.setCarNature(applyOrderInfo.getCarNature());
        return condition;
    }

    /**
     * 获取进件flag挂靠信息
     * @param condition
     * @param applyOrderInfo
     * @return
     */
    @Override
    public ApplyAppFormStateCondition getAffiliatedInfoArea(ApplyAppFormStateCondition condition,ApplyOrderInfo applyOrderInfo) {

        List<ApplyAffiliatedUnit> applyAffiliatedUnitList = applyAffiliatedUnitService.list(Wrappers.<ApplyAffiliatedUnit>query().lambda().eq(ApplyAffiliatedUnit::getApplyNo, condition.getApplyNo()));
        if(AffiliatedWay.NO.getIndex().equals(applyOrderInfo.getAffiliatedWay())){
            //挂靠方式无，前端无需验证是否已录入完成
            condition.setAffiliatedState(APP_FORM_STATE_ONE);
        }else{
            if(applyAffiliatedUnitList !=null && applyAffiliatedUnitList.size()>0){
                //是否已录入：是
                condition.setAffiliatedState(APP_FORM_STATE_ONE);
            }else{
                //是否已录入：否
                condition.setAffiliatedState(APP_FORM_STATE_ZERO);
            }
        }
        return condition;
    }

    /**
     * 获取进件flag资产信息
     * @param condition
     * @param applyOrderInfo
     * @return
     */
    @Override
    public ApplyAppFormStateCondition getAssetsInfoArea(ApplyAppFormStateCondition condition,ApplyOrderInfo applyOrderInfo) {
        List<ApplyCarDetails> applyCarDetailsList = applyCarDetailsService.list(Wrappers.<ApplyCarDetails>query().lambda().eq(ApplyCarDetails::getApplyNo, condition.getApplyNo()));
        if(applyCarDetailsList !=null && applyCarDetailsList.size()>0){
            //是否已录入：是
            condition.setAssetsState(APP_FORM_STATE_ONE);
            //业务类型：二手车 或者车辆属性：挂牌新车
            if(BUSINESS_TYPE_OLD_CAR.equals(applyOrderInfo.getBusinessType())|| CarNature.PLATE_CAR.getIndex().equals(applyOrderInfo.getCarNature())){
                //判断车牌号是否为空
                log.info("======================车辆手续信息区域组装开始========================》");
                if(!StrUtil.isBlank(applyCarDetailsList.get(0).getLicensePlate())){
                    //已录入车辆手续信息
                    condition.setCarFormAmitieState(APP_FORM_STATE_ONE);
                }else{
                    //未录入车辆手续信息
                    condition.setCarFormAmitieState(APP_FORM_STATE_ZERO);
                }
            }else{
                //未录入车辆手续信息
                condition.setCarFormAmitieState(APP_FORM_STATE_ONE);
            }
        }else{
            //是否已录入：否
            condition.setAssetsState(APP_FORM_STATE_ZERO);
            //业务类型：二手车 或者车辆属性：挂牌新车
            if(BUSINESS_TYPE_OLD_CAR.equals(applyOrderInfo.getBusinessType())|| CarNature.PLATE_CAR.getIndex().equals(applyOrderInfo.getCarNature())){
                //未录入车辆手续信息
                condition.setCarFormAmitieState(APP_FORM_STATE_ZERO);
            }else{
                //已录入车辆手续信息（特殊情况：如果业务无需录入信息：返回前端当作已录入处理）
                condition.setCarFormAmitieState(APP_FORM_STATE_ONE);
            }
        }
        if(APP_FORM_STATE_ONE.equals(condition.getBusinessTypeState()) &&
                APP_FORM_STATE_ONE.equals(condition.getAffiliatedState()) &&
                APP_FORM_STATE_ONE.equals(condition.getAssetsState()) &&
                APP_FORM_STATE_ONE.equals(condition.getCarFormAmitieState())){
            //当所有信息都是已录入情况更新  业务选择区域是否录入完成：是
            condition.setBusinessChoiceState(APP_FORM_STATE_ONE);
        }else{
            //当所有信息都是已录入情况更新  业务选择区域是否录入完成：否
            condition.setBusinessChoiceState(APP_FORM_STATE_ZERO);
        }
        return condition;
    }

    /**
     * 获取进件flag客户信息
     * @param condition
     * @param applyOrderInfo
     * @return
     */
    @Override
    public ApplyAppFormStateCondition getCustInfoArea(ApplyAppFormStateCondition condition,ApplyOrderInfo applyOrderInfo) {

        List<ApplyCustBaseInfo> custBaseInfos = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()));
        //主借人信息总状态
        condition.setMainManState(APP_FORM_STATE_ZERO);
        //主借人基本信息
        condition.setMainManBasicState(APP_FORM_STATE_ZERO);
        //主借人地址信息
        condition.setMainManAddressState(APP_FORM_STATE_ZERO);
        //主借人工作信息
        condition.setMainManWorkState(APP_FORM_STATE_ZERO);
        //主借人其他信息
        condition.setMainManOtherState(APP_FORM_STATE_ZERO);
        //担保人信息总状态
        condition.setWereBorrowedState(APP_FORM_STATE_ZERO);
        //担保人基本信息
        condition.setWereBorrowedBasicState(APP_FORM_STATE_ZERO);
        //担保人地址信息
        condition.setWereBorrowedAddressState(APP_FORM_STATE_ZERO);
        //担保人工作信息
        condition.setWereBorrowedWorkState(APP_FORM_STATE_ZERO);
        //共借人总状态
        condition.setGuarantorState(APP_FORM_STATE_ZERO);
        //共借人基本信息
        condition.setGuarantorBasicState(APP_FORM_STATE_ZERO);
        //共借人地址信息
        condition.setGuarantorAddressState(APP_FORM_STATE_ZERO);
        //共借人工作信息
        condition.setGuarantorWorkState(APP_FORM_STATE_ZERO);
        if(custBaseInfos !=null && custBaseInfos.size()>0 ){
            for(ApplyCustBaseInfo cust: custBaseInfos){
                if(PRINCIPAL_BORROWER.equals(cust.getCustRole())){
                    //主借人详细信息获取
                    ApplyCustPersonalDetail applyCustPersonalDetail = custPersonalService.getOne(Wrappers.<ApplyCustPersonalDetail>query().lambda()
                            .eq(ApplyCustPersonalDetail::getCustId, cust.getId()));
                    if(applyCustPersonalDetail !=null){
                        condition.setMainManMaritalStatus(applyCustPersonalDetail.getMaritalStatus());

                        if(StrUtil.isNotBlank(applyCustPersonalDetail.getDrivingType())){
                            //主借人其他信息录入判断关键字：驾驶证类型
                            condition.setMainManOtherState(APP_FORM_STATE_ONE);
                        }

                        if(StrUtil.isNotBlank(applyCustPersonalDetail.getUnitName()) && StrUtil.isNotBlank(applyCustPersonalDetail.getWorkAge())){
                            //主借人工作信息录入判断关键字：单位名称、工作年限
                            condition.setMainManWorkState(APP_FORM_STATE_ONE);
                        }


                        if(StrUtil.isNotBlank(cust.getCertNo()) && StrUtil.isNotBlank(applyCustPersonalDetail.getNationality()) ){
                            //主借人基本信息录入判断关键字：客户姓名，国籍
                            condition.setMainManBasicState(APP_FORM_STATE_ONE);
                        }

                    }
                    List<ApplyCustAddressDetails> detailsList = applyCustAddressService.list(Wrappers.<ApplyCustAddressDetails>query().lambda()
                            .eq(ApplyCustAddressDetails::getCustId, cust.getId()));
                    if(detailsList !=null && detailsList.size()>=2){
                        //主借人地址信息录入判断关键：至少已录入两条记录
                        condition.setMainManAddressState(APP_FORM_STATE_ONE);
                    }

                    //主借人其他信息已录入
                    if(APP_FORM_STATE_ONE.equals(condition.getMainManOtherState())
                            //主借人工作信息已录入
                            && APP_FORM_STATE_ONE.equals(condition.getMainManWorkState())
                            //主借人地址信息已录入
                            && APP_FORM_STATE_ONE.equals(condition.getMainManAddressState())
                            //主借人基本信息已录入
                            && APP_FORM_STATE_ONE.equals(condition.getMainManBasicState())){
                        //主借人总状态
                        condition.setMainManState(APP_FORM_STATE_ONE);
                    }
                }
                if(COMMON_BORROWER.equals(cust.getCustRole())){
                    //共借人详情查询
                    ApplyCustPersonalDetail applyCustPersonalDetail = custPersonalService.getOne(Wrappers.<ApplyCustPersonalDetail>query().lambda()
                            .eq(ApplyCustPersonalDetail::getCustId, cust.getId()));
                    if(applyCustPersonalDetail !=null){

                        if(StrUtil.isNotBlank(applyCustPersonalDetail.getUnitName()) && StrUtil.isNotBlank(applyCustPersonalDetail.getPosition())){
                            //共借人工作信息录入判断关键字：单位名称、职务
                            condition.setWereBorrowedWorkState(APP_FORM_STATE_ONE);
                        }

                        if(StrUtil.isNotBlank(cust.getCertNo()) && StrUtil.isNotBlank(applyCustPersonalDetail.getNationality()) ){
                            //共借人基本信息录入判断关键字：客户姓名，国籍
                            condition.setWereBorrowedBasicState(APP_FORM_STATE_ONE);
                        }
                    }
                    //共借人id
                    condition.setWereBorrowedId(cust.getId());
                    if(StrUtil.isBlank(cust.getIsLock())){
                        condition.setWereBorrowedIsLock(NO);
                    }else{
                        condition.setWereBorrowedIsLock(cust.getIsLock());
                    }

                    List<ApplyCustAddressDetails> detailsList = applyCustAddressService.list(Wrappers.<ApplyCustAddressDetails>query().lambda()
                            .eq(ApplyCustAddressDetails::getCustId, cust.getId()));
                    if(detailsList !=null && detailsList.size()>=2){
                        //主借人地址信息录入判断关键：至少已录入两条记录
                        condition.setWereBorrowedAddressState(APP_FORM_STATE_ONE);
                    }

                    //共借人工作信息已录入
                    if( APP_FORM_STATE_ONE.equals(condition.getWereBorrowedWorkState())
                            //共借人地址信息已录入
                            && APP_FORM_STATE_ONE.equals(condition.getWereBorrowedAddressState())
                            //共借人基本信息已录入
                            && APP_FORM_STATE_ONE.equals(condition.getWereBorrowedBasicState())){
                        //共借人总状态
                        condition.setWereBorrowedState(APP_FORM_STATE_ONE);
                    }
                }
                if(GUARANTOR.equals(cust.getCustRole())){
                    //担保人详情查询
                    ApplyCustPersonalDetail applyCustPersonalDetail = custPersonalService.getOne(Wrappers.<ApplyCustPersonalDetail>query().lambda()
                            .eq(ApplyCustPersonalDetail::getCustId, cust.getId()));
                    if(applyCustPersonalDetail !=null){

                        if(StrUtil.isNotBlank(applyCustPersonalDetail.getUnitName()) && StrUtil.isNotBlank(applyCustPersonalDetail.getPosition())){
                            //担保人工作信息录入判断关键字：单位名称、职务
                            condition.setGuarantorWorkState(APP_FORM_STATE_ONE);
                        }

                        if(StrUtil.isNotBlank(cust.getCertNo()) && StrUtil.isNotBlank(applyCustPersonalDetail.getNationality()) ){
                            //担保人基本信息录入判断关键字：客户姓名，国籍
                            condition.setGuarantorBasicState(APP_FORM_STATE_ONE);
                        }

                    }
                    //担保人id
                    condition.setGuarantorId(cust.getId());
                    if(StrUtil.isBlank(cust.getIsLock())){
                        condition.setGuarantorIsLock(NO);
                    }else{
                        condition.setGuarantorIsLock(cust.getIsLock());
                    }

                    List<ApplyCustAddressDetails> detailsList = applyCustAddressService.list(Wrappers.<ApplyCustAddressDetails>query().lambda()
                            .eq(ApplyCustAddressDetails::getCustId, cust.getId()));
                    if(detailsList !=null && detailsList.size()>=2){
                        //担保人地址信息录入判断关键：至少已录入两条记录
                        condition.setGuarantorAddressState(APP_FORM_STATE_ONE);
                    }

                    //担保人人工作信息已录入
                    if( APP_FORM_STATE_ONE.equals(condition.getGuarantorWorkState())
                            //担保人地址信息已录入
                            && APP_FORM_STATE_ONE.equals(condition.getGuarantorAddressState())
                            //担保人基本信息已录入
                            && APP_FORM_STATE_ONE.equals(condition.getGuarantorBasicState())){
                        //担保人总状态
                        condition.setGuarantorState(APP_FORM_STATE_ONE);
                    }
                }
            }
        }
        //紧急联系人
        condition.setEmergencyContactState(APP_FORM_STATE_ZERO);
        List<ApplyCustContacts> custContacts = applyCustContactsService.list(Wrappers.<ApplyCustContacts>query().lambda()
                .eq(ApplyCustContacts::getApplyNo, condition.getApplyNo()));
        if(custContacts !=null && custContacts.size()>=2 && StrUtil.isNotBlank(custContacts.get(0).getCustName()) &&
                StrUtil.isNotBlank(custContacts.get(0).getTelPhone()) && StrUtil.isNotBlank(custContacts.get(0).getCustRelation())){
            //紧急了联系人：已录入
            condition.setEmergencyContactState(APP_FORM_STATE_ONE);
        }
        if(APP_FORM_STATE_ONE.equals(condition.getEmergencyContactState()) &&
                APP_FORM_STATE_ONE.equals(condition.getMainManState()) ){
            //主借人与紧急联系人已录入 客户信息区域录入完成：是
            condition.setCustomerState(APP_FORM_STATE_ONE);
        }else{
            //主借人与紧急联系人已录入  客户信息区域是否录入完成：否
            condition.setCustomerState(APP_FORM_STATE_ZERO);
        }
        return condition;
    }

    /**
     * 获取进件flag 协议签约状态
     * @param condition
     * @return
     */
    @Override
    public ApplyAppFormStateCondition getSignInfoArea(ApplyAppFormStateCondition condition) {
        //关联签约关系表
        boolean signFlagBorrower = true;
        boolean signFlagCommon = true;
        boolean signFlagGuarantor = true;
        boolean errorFlagBorrower = false;
        boolean errorFlagCommon = false;
        boolean errorFlagGuarantor = false;
        condition.setSignedAgreementState(YES);
        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getBusinessNo,condition.getApplyNo()));
        if(signRelationList !=null && signRelationList.size()>0){
            for(ApplySignRelation relation: signRelationList){
                if(PRINCIPAL_BORROWER.equals(relation.getCustRole())){
                    if((NO.equals(relation.getStatus()) || StrUtil.isBlank(relation.getStatus()))){
                        condition.setSignedAgreementState(NO);
                        signFlagBorrower=false;
                    }
                }else if(COMMON_BORROWER.equals(relation.getCustRole())){
                    if((NO.equals(relation.getStatus()) || StrUtil.isBlank(relation.getStatus()))){
                        condition.setSignedAgreementState(NO);
                        signFlagCommon=false;
                    }
                }else if(GUARANTOR.equals(relation.getCustRole())){
                    if((NO.equals(relation.getStatus()) || StrUtil.isBlank(relation.getStatus()))){
                        condition.setSignedAgreementState(NO);
                        signFlagGuarantor=false;
                    }
                }
            }
        }
        boolean sfygjr=false;// 是否有共借人--需要查询出来
        boolean sfybzr=false;// 是否有保证人--需要查询出来
        ApplyCustBaseInfo infoBorrower = this.applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo())
                .eq(ApplyCustBaseInfo::getCustRole,PRINCIPAL_BORROWER));
        if(infoBorrower !=null){
            int signFailNumber =  infoBorrower.getSignFailNumber() == null ? 0 : infoBorrower.getSignFailNumber();
            if(signFailNumber >=3){
                errorFlagBorrower=true;
            }
        }

        ApplyCustBaseInfo infoCommon = this.applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo())
                .eq(ApplyCustBaseInfo::getCustRole,COMMON_BORROWER));
        if(infoCommon !=null){
            sfygjr=true;
            int signFailNumber =  infoCommon.getSignFailNumber() == null ? 0 : infoCommon.getSignFailNumber();
            if(signFailNumber >=3){
                errorFlagCommon=true;
            }
        }

        ApplyCustBaseInfo infoGuarantor = this.applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo())
                .eq(ApplyCustBaseInfo::getCustRole,GUARANTOR));
        if(infoGuarantor !=null){
            sfybzr=true;
            int signFailNumber =  infoGuarantor.getSignFailNumber() == null ? 0 : infoGuarantor.getSignFailNumber();
            if(signFailNumber >=3){
                errorFlagGuarantor=true;
            }
        }

        boolean borrower=false;
        boolean common=false;// 共借人
        boolean guarantor=false;// 保证人
        if(signFlagBorrower||errorFlagBorrower){
            borrower=true;
        }

        if(sfygjr&&(signFlagCommon||errorFlagCommon)){
            common=true;
        }

        if(sfybzr&&(signFlagGuarantor||errorFlagGuarantor)){
            guarantor=true;
        }
        condition.setSignApplyFlag(YES);
        if(!borrower){
            condition.setSignApplyFlag(NO);
        }
        if(sfygjr&&!common){
            condition.setSignApplyFlag(NO);
        }
        if(sfybzr&&!guarantor){
            condition.setSignApplyFlag(NO);
        }
        return condition;
    }

    /**
     * 获取进件flag 协议签约状态
     * @param condition
     * @return
     */
    @Override
    public ApplyAppFormStateCondition getAttachmentsArea(ApplyAppFormStateCondition condition,ApplyOrderInfo orderInfoByApplyNo) {

        FilterParamsVO filterParamsVO = new FilterParamsVO();
        //订单主表
        ApplyCarDetails carDetailsByApplyNo = this.applyCarDetailsService.getCarDetailsByApplyNo(condition.getApplyNo());
        //渠道信息表
        ApplyChannelInfo channelInfoByApplyNo = this.applyChannelInfoService.getChannelInfoByApplyNo(condition.getApplyNo());
        //融资项信息
        List<FinFinancingItems> applyFinancingItemsList = this.applyFinancingItemsService.getApplyFinancingItemsList(condition.getApplyNo());
        //融资信息
        List<FinCostDetails> costDetailsList = this.applyCostDetailsService.getCostDetailsList(condition.getApplyNo());
        //查询客户信息
        List<ApplyCustBaseInfo> custBaseInfoList = this.applyCustBaseInfoService.getCustBaseInfoList(condition.getApplyNo());
        //银行信息
        ApplyBankCard cardServiceOne = this.applyBankCardService.getOne(Wrappers.<ApplyBankCard>query().lambda()
                .eq(StringUtils.isNotBlank(condition.getApplyNo()), ApplyBankCard::getApplyNo, condition.getApplyNo()));
        //合同信息
        ApplyContractInfo contractInfoServiceOne = this.applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                .eq(StringUtils.isNotBlank(condition.getApplyNo()), ApplyContractInfo::getApplyNo, condition.getApplyNo()));
        //个人明细信息
        ApplyCustPersonalDetail personalDetailForMain = this.applyCustPersonalService.getPersonalDetailForMain(condition.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);

        if (ObjectUtil.isNotNull(orderInfoByApplyNo)) {
            //业务类型
            filterParamsVO.setBusinessType(orderInfoByApplyNo.getBusinessType());
            //挂靠方式
            filterParamsVO.setAffiliatedWay(orderInfoByApplyNo.getAffiliatedWay());
            //车辆属性
            filterParamsVO.setCarNature(orderInfoByApplyNo.getCarNature());
            //运营方式
            filterParamsVO.setOperateWay(orderInfoByApplyNo.getOperateWay());
            //是否网约车
            if (OperateWay.NETWORK_CAR.getIndex().equals(orderInfoByApplyNo.getOperateWay())) {
                filterParamsVO.setOnlineCar(WhetherEnum.YES.getIndex());
            } else {
                filterParamsVO.setOnlineCar(WhetherEnum.No.getIndex());
            }
            //车辆类型
            filterParamsVO.setCarType(orderInfoByApplyNo.getCarType());
        }
        if (ObjectUtil.isNotNull(channelInfoByApplyNo)) {
            //合作商名称
            filterParamsVO.setDealerName(channelInfoByApplyNo.getChannelName());
            //车商优质等级
            filterParamsVO.setDealerQualityGrade(channelInfoByApplyNo.getQualityGrade());
            //渠道归属
            filterParamsVO.setChannelBelong(channelInfoByApplyNo.getChannelBelong());
        }
        if (ObjectUtil.isNotNull(carDetailsByApplyNo)) {
            //车辆级别
            filterParamsVO.setCarBodyClass(carDetailsByApplyNo.getCarBodyClass());
            //是否新能源
            filterParamsVO.setIsGreen(carDetailsByApplyNo.getIsGreen());
        }
        if (CollectionUtil.isNotEmpty(applyFinancingItemsList)) {
            BigDecimal c = new BigDecimal("0.00");
            for (FinFinancingItems finFinancingItems : applyFinancingItemsList) {
                if (finFinancingItems.getFinanceItemAmt() != null) {
                    c = c.add(finFinancingItems.getFinanceItemAmt());
                }
            }
            //附加贷金额
            filterParamsVO.setAppendAmount(c);
        }
        if (CollectionUtil.isNotEmpty(costDetailsList)) {
            BigDecimal c = BigDecimal.ZERO;
            for (FinCostDetails finCostDetails : costDetailsList) {
                //金融产品
                if (ApplyConstants.COST_TYPE_CAR_LOAN.equals(finCostDetails.getCostType())) {
                    filterParamsVO.setProductId(finCostDetails.getProductId());
                }
                BigDecimal downPayScale = finCostDetails.getDownPayScale();
                BigDecimal bigDecimal1 = new BigDecimal("100");
                BigDecimal subtract = bigDecimal1.subtract(downPayScale);
                BigDecimal multiply = finCostDetails.getContractAmt().multiply(subtract);
                //车贷金额
                c = c.add(multiply.divide(bigDecimal1));
                //还款方式
                filterParamsVO.setRepayMode(finCostDetails.getAlgorithmType());
            }
            filterParamsVO.setCarLoanAmount(c);
        }
        //车贷
        if (CollectionUtil.isNotEmpty(custBaseInfoList)) {
            custBaseInfoList.forEach(applyCustBaseInfo -> {
                //是否有共借人
                if (ApplyConstants.COMMON_BORROWER.equals(applyCustBaseInfo.getCustRole())) {
                    filterParamsVO.setHasCommonBorrower(WhetherEnum.YES.getIndex());
                } else {
                    filterParamsVO.setHasCommonBorrower(WhetherEnum.No.getIndex());
                }
                //是否有保证人
                if (ApplyConstants.GUARANTOR.equals(applyCustBaseInfo.getCustRole())) {
                    filterParamsVO.setHasBail(WhetherEnum.YES.getIndex());
                } else {
                    filterParamsVO.setHasBail(WhetherEnum.No.getIndex());
                }
            });
        }
        if (ObjectUtil.isNotNull(cardServiceOne)) {
            //还款卡银行
            filterParamsVO.setBankCode(cardServiceOne.getBankCode());
            //是否电子授权
            if ("offline".equals(cardServiceOne.getAuthorizeWay())) {
                filterParamsVO.setLendingMode(WhetherEnum.No.getIndex());
            } else if ("online".equals(cardServiceOne.getAuthorizeWay())) {
                filterParamsVO.setLendingMode(WhetherEnum.YES.getIndex());
            }
        }
        //放款模式
        if (ObjectUtil.isNotNull(contractInfoServiceOne)) {
            filterParamsVO.setLendingMode(contractInfoServiceOne.getLendingMode());
            filterParamsVO.setContractNo(contractInfoServiceOne.getContractNo());
        }
        if (ObjectUtil.isNotNull(personalDetailForMain)) {
            //是否存在档案编号
            if (StringUtil.isNotEmpty(personalDetailForMain.getDrivingLicenceNo())) {
                filterParamsVO.setHasLicenseNum(WhetherEnum.YES.getIndex());
            } else {
                filterParamsVO.setHasLicenseNum(WhetherEnum.No.getIndex());
            }
            //驾驶证件
            if (StringUtil.isNotEmpty(personalDetailForMain.getDrivingType())) {
                filterParamsVO.setDrivingType(personalDetailForMain.getDrivingType());
            }
        }
        List<String> errorMsgList= new ArrayList<>();
        String busiNo = condition.getBusiNo();
        String busiType = condition.getBusiType();
        JSONObject json = (JSONObject) JSONObject.toJSON(filterParamsVO);
        List<ComAttachmentManagement> managementList = comAttaManageService.getManagementByRuleGroup(json, busiType);
        managementList.forEach(comAttachmentManagement -> {
            List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().
                    eq(ComAttachmentFile::getAttachmentCode, String.valueOf(comAttachmentManagement.getId()))
                    .eq(ComAttachmentFile::getBusiNo, busiNo));
            comAttachmentManagement.setFileList(fileList);
            if(comAttachmentManagement.getAttachmentClass()== AttachmentClassEnum.SUBCLASS.getCode() &&comAttachmentManagement.getNeedNums()>fileList.size()){
                errorMsgList.add(comAttachmentManagement.getAttachmentName());
            }
        });

        Map<Long, List<ComAttachmentManagement>> subclassAttachmentManagementMaps = managementList.stream()
                .collect(Collectors.groupingBy(ComAttachmentManagement::getParentId));
        managementList.forEach(management->{
            if(management.getAttachmentClass()==AttachmentClassEnum.GROUP.getCode()){
                int filenums=0;
                List<ComAttachmentManagement> attachmentManagementList=subclassAttachmentManagementMaps.get(management.getId());
                if(!CollectionUtils.isEmpty(attachmentManagementList)){
                    for(ComAttachmentManagement comAttachmentManagement : attachmentManagementList){
                        if(comAttachmentManagement.getFileList().size()>0){
                            filenums=filenums+1;
                        }
                    }
                    if(management.getNeedNums()>filenums){
                        errorMsgList.add(management.getAttachmentName());
                    }
                }
            }
        });
        if(errorMsgList.size()>0){
            condition.setImageAttachmentsState(APP_FORM_STATE_ZERO);
            condition.setErrorMsg(errorMsgList.toString());
        }else{
            condition.setImageAttachmentsState(APP_FORM_STATE_ONE);
        }
        return condition;
    }

    /**
     * 获取放款flag发票信息
     * @param condition
     * @param applyOrderInfo
     * @return
     */
    @Override
    public LoanAppFormStateCondition getInvoiceTypeArea(LoanAppFormStateCondition condition,ApplyOrderInfo applyOrderInfo) {
        List<ApplyCarInvoice> carInvoiceList = applyCarInvoiceService.list(Wrappers.<ApplyCarInvoice>query().lambda().eq(ApplyCarInvoice::getApplyNo, condition.getApplyNo()));
        if(carInvoiceList !=null && carInvoiceList.size()>0){
            if(BUSINESS_TYPE_NEW_CAR.equals(condition.getBusinessType())){
                if(StrUtil.isBlank(carInvoiceList.get(0).getInvoiceUnit())){
                    //新车验证关键字开票单位是否已录入
                    condition.setInvoiceState(APP_FORM_STATE_ZERO);
                }else{
                    condition.setInvoiceState(APP_FORM_STATE_ONE);
                }
            }else{
                //二手车验证开票单位性质
                if(StrUtil.isBlank(carInvoiceList.get(0).getInvoiceNature())){
                    condition.setInvoiceState(APP_FORM_STATE_ZERO);
                }else{
                    //二手车根据开票单位性质动态验证：个人验证出卖方名称；企业验证开票单位名称
                    if("personal".equals(carInvoiceList.get(0).getInvoiceNature())){
                        if(StrUtil.isBlank(carInvoiceList.get(0).getSaleName())){
                            condition.setInvoiceState(APP_FORM_STATE_ZERO);
                        }else{
                            condition.setInvoiceState(APP_FORM_STATE_ONE);
                        }
                    }else{
                        if(StrUtil.isBlank(carInvoiceList.get(0).getInvoiceUnit())){
                            condition.setInvoiceState(APP_FORM_STATE_ZERO);
                        }else{
                            condition.setInvoiceState(APP_FORM_STATE_ONE);
                        }
                    }
                }
            }
        }else{
            condition.setInvoiceState(APP_FORM_STATE_ZERO);
        }
        return condition;
    }

    /**
     * 获取放款flagGps信息
     * @param condition
     * @param applyOrderInfo
     * @param contractInfo
     * @return
     */
    @Override
    public LoanAppFormStateCondition getGpsInfoArea(LoanAppFormStateCondition condition,ApplyOrderInfo applyOrderInfo,ApplyContractInfo contractInfo) {
        List<ApplyGpsInfo> gpsList = applyGpsInfoService.list(Wrappers.<ApplyGpsInfo>query().lambda().eq(ApplyGpsInfo::getApplyNo, condition.getApplyNo()));
        if(gpsList !=null && gpsList.size()>0){
            //考虑多条情况、目前只有一条
            for(ApplyGpsInfo gpsInfo :gpsList){
                if(!StrUtil.isBlank(gpsInfo.getOrderNo())){
                    condition.setGpsState(APP_FORM_STATE_ONE);
                }else{
                    condition.setGpsState(APP_FORM_STATE_ZERO);
                    //跳出此次循环
                    break;
                }
            }
        }else{
            condition.setGpsState(APP_FORM_STATE_ZERO);
        }
        condition.setGpsApplyStatus(contractInfo.getGpsStatus());
        condition.setIsGpsState(APP_FORM_STATE_ONE);
        String gpsRule = gpsRule(applyOrderInfo);
        if ("noInstall".equals(gpsRule)) {
            //无需录入Gps信息特殊情况
            condition.setIsGpsState(APP_FORM_STATE_ZERO);
        }
        return condition;
    }

    /**
     * 获取Gps规则信息
     * @param orderInfo
     * @return
     */
    public String gpsRule(ApplyOrderInfo orderInfo) {
        JSONObject runParams=new JSONObject();
        String isGreatWall= ApplyConstants.UN_GREAT_WALL;

        String isInternet;
        List<FinCostDetails> costDetails = applyCostDetailsService.list(Wrappers.<FinCostDetails>query().lambda().eq(FinCostDetails::getApplyNo, orderInfo.getApplyNo()).eq(FinCostDetails::getCostType, ApplyConstants.COST_TYPE_CAR_LOAN));
        ApplyCarDetails carDetails = applyCarDetailsService.getOne(Wrappers.<ApplyCarDetails>query().lambda().eq(ApplyCarDetails::getApplyNo, orderInfo.getApplyNo()));
        if(carDetails.getBrandName().indexOf(ApplyConstants.IS_GREAT_WALL)>=0){
            isGreatWall=ApplyConstants.GREAT_WALL;
        }
        if(StrUtil.isBlank(carDetails.getIsInternet()) || carDetails.getIsInternet().equals(ApplyConstants.UN_INTERNET)){
            isInternet=ApplyConstants.IS_NOT_INTERNET;
        }else{
            isInternet=ApplyConstants.IS_INTERNET;
        }
        BigDecimal loanAmt=BigDecimal.ZERO;
        for (FinCostDetails applyCostDetails : costDetails) {
            loanAmt=loanAmt.add(applyCostDetails.getLoanAmt());
        }
        //是否长城品牌
        runParams.put("isGreatWall",isGreatWall);
        //业务类型
        runParams.put("businessType",orderInfo.getBusinessType());
        //车辆类型
        runParams.put("carType",orderInfo.getCarType());
        //车辆属性
        runParams.put("carNature",orderInfo.getCarNature());
        //是否车联网
        runParams.put("isOnline",isInternet);
        //贷款总额
        runParams.put("loanAmount",String.valueOf(loanAmt));
        //挂靠方式
        runParams.put("affiliatedWay",orderInfo.getAffiliatedWay());
        List<LoanGpsRuleInfo> rules = loanGpsRuleInfoService.list();
        List<String> ruleNoList = rules.stream().map(s -> String.valueOf(s.getId())).collect(Collectors.toList());
        RuleRunResult ruleRunResult = RuleHelper.runRule(runParams, ruleNoList, true, RuleRunEnum.SERIAL);
        if(ruleRunResult.getResults().size()>0){
            LoanGpsRuleInfo loanGpsRuleInfo=loanGpsRuleInfoService.getById(ruleRunResult.getResults().get(0).getRuleNo());
            if(loanGpsRuleInfo!=null){
                return loanGpsRuleInfo.getInstallType();
            }
        }
        return null;
    }

    /**
     * 获取放款flag附加带信息
     * @param condition
     * @return
     */
    @Override
    public LoanAppFormStateCondition getFinancingItemsArea(LoanAppFormStateCondition condition) {
        List<FinFinancingItems> finFinancingItemsList = financingItemsService.list(Wrappers.<FinFinancingItems>query().lambda().eq(FinFinancingItems::getApplyNo, condition.getApplyNo()));
        if(finFinancingItemsList !=null && finFinancingItemsList.size()>0){
            //是否附加贷业务：否
            condition.setIsAttachedInfoState(APP_FORM_STATE_ZERO);
            for(FinFinancingItems items: finFinancingItemsList){
                if(Boolean.TRUE.equals(items.getIsView())){
                    //附加贷业务是否展示：是
                    condition.setIsAttachedInfoState(APP_FORM_STATE_ONE);
                    break;
                }else{
                    //附加贷业务是否展示：是
                    condition.setIsAttachedInfoState(APP_FORM_STATE_ZERO);
                }
            }
        }else{
            //是否附加贷业务：否
            condition.setIsAttachedInfoState(APP_FORM_STATE_ZERO);
        }
        List<ApplyAddPriceItems> addPriceItems = applyAddPriceItemsService.list(Wrappers.<ApplyAddPriceItems>query().lambda().eq(ApplyAddPriceItems::getApplyNo, condition.getApplyNo()));
        if(addPriceItems !=null && addPriceItems.size()>0){
            for(ApplyAddPriceItems items: addPriceItems){
                BigDecimal addFinanceAmt = items.getAddFinanceAmt() == null ? BigDecimal.ZERO : items.getAddFinanceAmt();
                if(addFinanceAmt.compareTo(BigDecimal.ZERO)==0){
                    //附加贷业务是否录入：否
                    condition.setAttachedInfoState(APP_FORM_STATE_ZERO);
                    break;
                }else{
                    //附加贷业务是否录入：是
                    condition.setAttachedInfoState(APP_FORM_STATE_ONE);
                }
            }
        }else{
            //附加贷业务是否录入：否
            condition.setAttachedInfoState(APP_FORM_STATE_ZERO);
        }
        return condition;
    }

    /**
     * 获取放款flag证件有效期信息
     * @param condition
     * @return
     */
    @Override
    public LoanAppFormStateCondition getCustInfoArea(LoanAppFormStateCondition condition) {

        ApplyCustHistory custHistory = applyCustHistoryService.getOne(Wrappers.<ApplyCustHistory>query().lambda()
                .eq(ApplyCustHistory::getApplyNo, condition.getApplyNo())
                .eq(ApplyCustHistory::getCustRole, PRINCIPAL_BORROWER));
        if(custHistory !=null){
            if(Boolean.TRUE.equals(custHistory.getIsLongTerm())){
                condition.setCertificateMainState(CERTIFICATE_STATE_TWO);
            }else{
                Date certEndDate=custHistory.getCertEndDate();
                Date date = new Date();
                long diff = certEndDate.getTime() - date.getTime();
                long days = diff / (1000 * 60 * 60 * 24);
                if(certEndDate.after(date) && days<=15){
                    //还有15天就要到期了
                    condition.setCertificateMainState(CERTIFICATE_STATE_ONE);
                }else if(certEndDate.before(date)){
                    //已到期
                    condition.setCertificateMainState(CERTIFICATE_STATE_ZERO);
                }else{
                    //未到期
                    condition.setCertificateMainState(CERTIFICATE_STATE_TWO);
                }
            }
        }else{
            ApplyCustBaseInfo mainCustInfo = this.applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                    .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER));
            if(mainCustInfo !=null){
                if(Boolean.TRUE.equals(mainCustInfo.getIsLongTerm())){
                    condition.setCertificateMainState(CERTIFICATE_STATE_TWO);
                }else{
                    Date certEndDate=mainCustInfo.getCertEndDate();
                    Date date = new Date();
                    long diff = certEndDate.getTime() - date.getTime();
                    long days = diff / (1000 * 60 * 60 * 24);
                    if(certEndDate.after(date) && days<=15){
                        //还有15天就要到期了
                        condition.setCertificateMainState(CERTIFICATE_STATE_ONE);
                    }else if(certEndDate.before(date)){
                        //已到期
                        condition.setCertificateMainState(CERTIFICATE_STATE_ZERO);
                    }else{
                        //未到期
                        condition.setCertificateMainState(CERTIFICATE_STATE_TWO);
                    }
                }
            }
        }

        ApplyCustHistory custBorrower = applyCustHistoryService.getOne(Wrappers.<ApplyCustHistory>query().lambda()
                .eq(ApplyCustHistory::getApplyNo, condition.getApplyNo())
                .eq(ApplyCustHistory::getCustRole, COMMON_BORROWER));
        if(custBorrower !=null){
            if(Boolean.TRUE.equals(custBorrower.getIsLongTerm())){
                condition.setCertificateBorrowedState(CERTIFICATE_STATE_TWO);
            }else{
                Date certEndDate=custBorrower.getCertEndDate();
                Date date = new Date();
                long diff = certEndDate.getTime() - date.getTime();
                long days = diff / (1000 * 60 * 60 * 24);
                if(certEndDate.after(date) && days<=15){
                    //还有15天就要到期了
                    condition.setCertificateBorrowedState(CERTIFICATE_STATE_ONE);
                }else if(certEndDate.before(date)){
                    //已到期
                    condition.setCertificateBorrowedState(CERTIFICATE_STATE_ZERO);
                }else{
                    //未到期
                    condition.setCertificateBorrowedState(CERTIFICATE_STATE_TWO);
                }
            }
        }else{
            ApplyCustBaseInfo borrowerCustInfo = this.applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                    .eq(ApplyCustBaseInfo::getApplyNo, condition.getApplyNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.COMMON_BORROWER));
            if(borrowerCustInfo !=null){
                if(Boolean.TRUE.equals(borrowerCustInfo.getIsLongTerm())){
                    condition.setCertificateBorrowedState(CERTIFICATE_STATE_TWO);
                }else{
                    Date certEndDate=borrowerCustInfo.getCertEndDate();
                    Date date = new Date();
                    long diff = certEndDate.getTime() - date.getTime();
                    long days = diff / (1000 * 60 * 60 * 24);
                    if(certEndDate.after(date) && days<=15){
                        //还有15天就要到期了
                        condition.setCertificateBorrowedState(CERTIFICATE_STATE_ONE);
                    }else if(certEndDate.before(date)){
                        //已到期
                        condition.setCertificateBorrowedState(CERTIFICATE_STATE_ZERO);
                    }else{
                        //未到期
                        condition.setCertificateBorrowedState(CERTIFICATE_STATE_TWO);
                    }
                }
            }
        }
        return condition;
    }

    /**
     * 获取放款flag总状态信息
     * @param condition
     * @return
     */
    @Override
    public LoanAppFormStateCondition getOtherInfoArea(LoanAppFormStateCondition condition) {
        if(APP_FORM_STATE_ONE.equals(condition.getInvoiceState()) && APP_FORM_STATE_ONE.equals(condition.getGpsState()) &&
                APP_FORM_STATE_ONE.equals(condition.getBankCardState()) && APP_FORM_STATE_ONE.equals(condition.getBankCardState()) &&
                APP_FORM_STATE_ONE.equals(condition.getAffiliatedState())){
            //当所有信息都是已录入情况更新是否录入完成：是
            condition.setLoanInfoState(APP_FORM_STATE_ONE);
        }else{
            condition.setLoanInfoState(APP_FORM_STATE_ZERO);
        }

        //主借人是否签约
        condition.setSignMainManState(APP_FORM_STATE_ONE);
        //共借人是否签约
        condition.setSignWereBorrowedState(APP_FORM_STATE_ONE);
        //保证人是否签约
        condition.setSignGuarantorState(APP_FORM_STATE_ONE);
        //见证人是否签约
        condition.setSignWitnessesState(APP_FORM_STATE_ONE);
        //车商是否签约
        condition.setSignCarDealerState(APP_FORM_STATE_ONE);
        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                .eq(ApplySignRelation::getBusinessNo,condition.getContractNo()));
        if(signRelationList !=null && signRelationList.size()>0){
            for(ApplySignRelation relation: signRelationList){
                if(YES.equals(relation.getStatus())){
                    condition.setIsNeedSign(APP_FORM_STATE_ONE);
                    break;
                }else{
                    condition.setIsNeedSign(APP_FORM_STATE_ZERO);
                }
            }

            for(ApplySignRelation signRelation: signRelationList){
                if(ApplyConstants.PRINCIPAL_BORROWER.equals(signRelation.getCustRole()) && NO.equals(signRelation.getStatus())){
                    //主借人状态变更成未签约
                    condition.setSignMainManState(APP_FORM_STATE_ZERO);
                }else if(ApplyConstants.COMMON_BORROWER.equals(signRelation.getCustRole()) && NO.equals(signRelation.getStatus())){
                    //共借人状态变更成未签约
                    condition.setSignWereBorrowedState(APP_FORM_STATE_ZERO);
                }else if(ApplyConstants.GUARANTOR.equals(signRelation.getCustRole()) && NO.equals(signRelation.getStatus())){
                    //担保人状态变更成未签约
                    condition.setSignGuarantorState(APP_FORM_STATE_ZERO);
                }else if(ApplyConstants.WITNESSES.equals(signRelation.getCustRole()) && NO.equals(signRelation.getStatus())){
                    //见证人状态变更成未签约
                    condition.setSignWitnessesState(APP_FORM_STATE_ZERO);
                }else if(ApplyConstants.CAR_DEALER.equals(signRelation.getCustRole()) && NO.equals(signRelation.getStatus())){
                    //车商状态变更成未签约
                    condition.setSignCarDealerState(APP_FORM_STATE_ZERO);
                }
            }
        }else{
            //表示没有生成电子签合同，所以是否必须电子签为否
            condition.setIsNeedSign(APP_FORM_STATE_ZERO);
        }

        if(APP_FORM_STATE_ONE.equals(condition.getSignMainManState()) && APP_FORM_STATE_ONE.equals(condition.getSignWereBorrowedState()) &&
                APP_FORM_STATE_ONE.equals(condition.getBankCardState()) && APP_FORM_STATE_ONE.equals(condition.getSignGuarantorState()) &&
                APP_FORM_STATE_ONE.equals(condition.getSignWitnessesState()) && APP_FORM_STATE_ONE.equals(condition.getSignCarDealerState()) ){
            //合同签约总状态
            condition.setSignContractState(APP_FORM_STATE_ONE);
        }else{
            condition.setSignContractState(APP_FORM_STATE_ZERO);
        }
        return condition;
    }

    /**
     * 获取放款签约见证人
     * @param user
     * @return
     */
    @Override
    public LoanAppSignPeopleListCondition getWitnessesInfo(AfsUser user,LoanAppSignPeopleListCondition condition) {
        LoanAppSignPeopleListCondition witnessesCondition = new LoanAppSignPeopleListCondition();
        IResponse vo = applyAdminService.getUserInfoByUsername(user.getUsername());
        //申请编号
        witnessesCondition.setApplyNo(condition.getApplyNo());
        witnessesCondition.setCustRole(WITNESSES);
        if("0000".equals(vo.getCode())){
            Map map = (Map) vo.getData();
            //客户姓名
            witnessesCondition.setCustName(user.getUserRealName());
            //证件号码
            witnessesCondition.setCertNo((String) map.get("identityNumber"));
            //手机号码
            witnessesCondition.setTelPhone((String) map.get("phone"));
            //签约人主键id
            witnessesCondition.setId(user.getId());
        }

        //关联合同信息表
        ApplyContractInfo contractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                .eq(ApplyContractInfo::getApplyNo, condition.getApplyNo()));
        if(contractInfo !=null){
            //合同号赋值
            witnessesCondition.setContractNo(contractInfo.getContractNo());
        }else{
            witnessesCondition.setContractNo("");
        }
        //关联签约关系表
        if(StrUtil.isNotBlank(witnessesCondition.getContractNo())){
            List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                    .eq(ApplySignRelation::getCustId, user.getId())
                    .eq(ApplySignRelation::getBusinessNo,witnessesCondition.getContractNo())
                    .eq(ApplySignRelation::getCustRole,witnessesCondition.getCustRole()));
            if(signRelationList !=null && signRelationList.size()>0){
                for(ApplySignRelation relation: signRelationList){
                    if(NO.equals(relation.getStatus()) || StrUtil.isBlank(relation.getStatus())){
                        witnessesCondition.setSignState(NO);
                        break;
                    }else{
                        witnessesCondition.setSignState(YES);
                        witnessesCondition.setSignDate(relation.getUpdateTime());
                    }
                }
            }
        }else{
            witnessesCondition.setSignState(NO);
        }
        return witnessesCondition;
    }

    /**
     * 获取放款签约车商信息
     * @param condition
     * @return
     */
    @Override
    public LoanAppSignPeopleListCondition geCarDealerInfo(LoanAppSignPeopleListCondition condition,ApplyCarInvoice applyCarInvoice) {
        LoanAppSignPeopleListCondition carDealerCondition = new LoanAppSignPeopleListCondition();
        //申请编号
        carDealerCondition.setApplyNo(condition.getApplyNo());
        carDealerCondition.setCustRole(CAR_DEALER);
        if(applyCarInvoice !=null){
            //客户姓名
            carDealerCondition.setCustName(applyCarInvoice.getSaleName());
            //证件号码
            carDealerCondition.setCertNo(applyCarInvoice.getSaleCertNo());
            //手机号码
            carDealerCondition.setTelPhone(applyCarInvoice.getSalePhone());
            //签约人主键id
            carDealerCondition.setId(applyCarInvoice.getId());
            //关联合同信息表
            ApplyContractInfo contractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                    .eq(ApplyContractInfo::getApplyNo, condition.getApplyNo()));
            if(contractInfo !=null){
                //合同号赋
                carDealerCondition.setContractNo(contractInfo.getContractNo());
            }else{
                carDealerCondition.setContractNo("");
            }
            //关联签约关系表
            if(StrUtil.isNotBlank(carDealerCondition.getContractNo())){
                List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                        .eq(ApplySignRelation::getCustId, carDealerCondition.getId())
                        .eq(ApplySignRelation::getBusinessNo,carDealerCondition.getContractNo())
                        .eq(ApplySignRelation::getCustRole,carDealerCondition.getCustRole()));
                if(signRelationList !=null && signRelationList.size()>0){
                    for(ApplySignRelation relation: signRelationList){
                        if(NO.equals(relation.getStatus()) || StrUtil.isBlank(relation.getStatus())){
                            carDealerCondition.setSignState(NO);
                            break;
                        }else{
                            carDealerCondition.setSignState(YES);
                            carDealerCondition.setSignDate(relation.getUpdateTime());
                        }
                    }
                }
            }else{
                carDealerCondition.setSignState(NO);
            }
            return carDealerCondition;
        }
        return carDealerCondition;
    }
    /**
     * 获取放款flag 附件状态
     * @param condition
     * @return
     */
    @Override
    public LoanAppFormStateCondition getLoanAttachmentsArea(LoanAppFormStateCondition condition,ApplyOrderInfo orderInfoByApplyNo) {

        FilterParamsVO filterParamsVO = new FilterParamsVO();
        //订单主表
        ApplyCarDetails carDetailsByApplyNo = this.applyCarDetailsService.getCarDetailsByApplyNo(condition.getApplyNo());
        //渠道信息表
        ApplyChannelInfo channelInfoByApplyNo = this.applyChannelInfoService.getChannelInfoByApplyNo(condition.getApplyNo());
        //融资项信息
        List<FinFinancingItems> applyFinancingItemsList = this.applyFinancingItemsService.getApplyFinancingItemsList(condition.getApplyNo());
        //融资信息
        List<FinCostDetails> costDetailsList = this.applyCostDetailsService.getCostDetailsList(condition.getApplyNo());
        //查询客户信息
        List<ApplyCustBaseInfo> custBaseInfoList = this.applyCustBaseInfoService.getCustBaseInfoList(condition.getApplyNo());
        //银行信息
        ApplyBankCard cardServiceOne = this.applyBankCardService.getOne(Wrappers.<ApplyBankCard>query().lambda()
                .eq(StringUtils.isNotBlank(condition.getApplyNo()), ApplyBankCard::getApplyNo, condition.getApplyNo()));
        //合同信息
        ApplyContractInfo contractInfoServiceOne = this.applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda()
                .eq(StringUtils.isNotBlank(condition.getApplyNo()), ApplyContractInfo::getApplyNo, condition.getApplyNo()));
        //个人明细信息
        ApplyCustPersonalDetail personalDetailForMain = this.applyCustPersonalService.getPersonalDetailForMain(condition.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
        // 发票信息
        List<ApplyCarInvoice> applyCarInvoiceList = applyCarInvoiceService.list(Wrappers.<ApplyCarInvoice>query().lambda()
                .eq(ApplyCarInvoice::getApplyNo, condition.getApplyNo()).orderByAsc(ApplyCarInvoice::getCreateTime));
        if (applyCarInvoiceList != null && applyCarInvoiceList.size() > 0) {
            filterParamsVO.setMakeInvoiceUnit(applyCarInvoiceList.get(0).getInvoiceUnit());
        }
        if (ObjectUtil.isNotNull(orderInfoByApplyNo)) {
            //业务类型
            filterParamsVO.setBusinessType(orderInfoByApplyNo.getBusinessType());
            //挂靠方式
            filterParamsVO.setAffiliatedWay(orderInfoByApplyNo.getAffiliatedWay());
            //车辆属性
            filterParamsVO.setCarNature(orderInfoByApplyNo.getCarNature());
            //运营方式
            filterParamsVO.setOperateWay(orderInfoByApplyNo.getOperateWay());
            //是否网约车
            if (OperateWay.NETWORK_CAR.getIndex().equals(orderInfoByApplyNo.getOperateWay())) {
                filterParamsVO.setOnlineCar(WhetherEnum.YES.getIndex());
            } else {
                filterParamsVO.setOnlineCar(WhetherEnum.No.getIndex());
            }
            //车辆类型
            filterParamsVO.setCarType(orderInfoByApplyNo.getCarType());
        }
        if (ObjectUtil.isNotNull(channelInfoByApplyNo)) {
            //合作商名称
            filterParamsVO.setDealerName(channelInfoByApplyNo.getChannelName());
            //车商优质等级
            filterParamsVO.setDealerQualityGrade(channelInfoByApplyNo.getQualityGrade());
            //渠道归属
            filterParamsVO.setChannelBelong(channelInfoByApplyNo.getChannelBelong());
        }
        if (ObjectUtil.isNotNull(carDetailsByApplyNo)) {
            //车辆级别
            filterParamsVO.setCarBodyClass(carDetailsByApplyNo.getCarBodyClass());
            //是否新能源
            filterParamsVO.setIsGreen(carDetailsByApplyNo.getIsGreen());
        }
        if (CollectionUtil.isNotEmpty(applyFinancingItemsList)) {
            BigDecimal c = new BigDecimal("0.00");
            for (FinFinancingItems finFinancingItems : applyFinancingItemsList) {
                if (finFinancingItems.getFinanceItemAmt() != null) {
                    c = c.add(finFinancingItems.getFinanceItemAmt());
                }
            }
            //附加贷金额
            filterParamsVO.setAppendAmount(c);
        }
        if (CollectionUtil.isNotEmpty(costDetailsList)) {
            BigDecimal c = BigDecimal.ZERO;
            for (FinCostDetails finCostDetails : costDetailsList) {
                //金融产品
                if (ApplyConstants.COST_TYPE_CAR_LOAN.equals(finCostDetails.getCostType())) {
                    filterParamsVO.setProductId(finCostDetails.getProductId());
                }
                BigDecimal downPayScale = finCostDetails.getDownPayScale();
                BigDecimal bigDecimal1 = new BigDecimal("100");
                BigDecimal subtract = bigDecimal1.subtract(downPayScale);
                BigDecimal multiply = finCostDetails.getContractAmt().multiply(subtract);
                //车贷金额
                c = c.add(multiply.divide(bigDecimal1));
                //还款方式
                filterParamsVO.setRepayMode(finCostDetails.getAlgorithmType());
            }
            filterParamsVO.setCarLoanAmount(c);
        }
        //车贷
        if (CollectionUtil.isNotEmpty(custBaseInfoList)) {
            custBaseInfoList.forEach(applyCustBaseInfo -> {
                //是否有共借人
                if (ApplyConstants.COMMON_BORROWER.equals(applyCustBaseInfo.getCustRole())) {
                    filterParamsVO.setHasCommonBorrower(WhetherEnum.YES.getIndex());
                } else {
                    filterParamsVO.setHasCommonBorrower(WhetherEnum.No.getIndex());
                }
                //是否有保证人
                if (ApplyConstants.GUARANTOR.equals(applyCustBaseInfo.getCustRole())) {
                    filterParamsVO.setHasBail(WhetherEnum.YES.getIndex());
                } else {
                    filterParamsVO.setHasBail(WhetherEnum.No.getIndex());
                }
            });
        }
        if (ObjectUtil.isNotNull(cardServiceOne)) {
            //还款卡银行
            filterParamsVO.setBankCode(cardServiceOne.getBankCode());
            //是否电子授权
            if ("offline".equals(cardServiceOne.getAuthorizeWay())) {
                filterParamsVO.setLendingMode(WhetherEnum.No.getIndex());
            } else if ("online".equals(cardServiceOne.getAuthorizeWay())) {
                filterParamsVO.setLendingMode(WhetherEnum.YES.getIndex());
            }
        }
        //放款模式
        if (ObjectUtil.isNotNull(contractInfoServiceOne)) {
            filterParamsVO.setLendingMode(contractInfoServiceOne.getLendingMode());
            filterParamsVO.setContractNo(contractInfoServiceOne.getContractNo());
        }
        if (ObjectUtil.isNotNull(personalDetailForMain)) {
            //是否存在档案编号
            if (StringUtil.isNotEmpty(personalDetailForMain.getDrivingLicenceNo())) {
                filterParamsVO.setHasLicenseNum(WhetherEnum.YES.getIndex());
            } else {
                filterParamsVO.setHasLicenseNum(WhetherEnum.No.getIndex());
            }
            //驾驶证件
            if (StringUtil.isNotEmpty(personalDetailForMain.getDrivingType())) {
                filterParamsVO.setDrivingType(personalDetailForMain.getDrivingType());
            }
        }
        List<String> errorMsgList= new ArrayList<>();
        String busiNo = condition.getBusiNo();
        String busiType = condition.getBusiType();
        JSONObject json = (JSONObject) JSONObject.toJSON(filterParamsVO);
        List<ComAttachmentManagement> managementList = comAttaManageService.getManagementByRuleGroup(json, busiType);
        managementList.forEach(comAttachmentManagement -> {
            List<ComAttachmentFile> fileList = comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().
                    eq(ComAttachmentFile::getAttachmentCode, String.valueOf(comAttachmentManagement.getId()))
                    .eq(ComAttachmentFile::getBusiNo, busiNo));
            comAttachmentManagement.setFileList(fileList);
            if(comAttachmentManagement.getAttachmentClass()== AttachmentClassEnum.SUBCLASS.getCode() &&comAttachmentManagement.getNeedNums()>fileList.size()){
                errorMsgList.add(comAttachmentManagement.getAttachmentName());
            }
        });

        Map<Long, List<ComAttachmentManagement>> subclassAttachmentManagementMaps = managementList.stream()
                .collect(Collectors.groupingBy(ComAttachmentManagement::getParentId));
        managementList.forEach(management->{
            if(management.getAttachmentClass()==AttachmentClassEnum.GROUP.getCode()){
                int filenums=0;
                List<ComAttachmentManagement> attachmentManagementList=subclassAttachmentManagementMaps.get(management.getId());
                if(!CollectionUtils.isEmpty(attachmentManagementList)){
                    for(ComAttachmentManagement comAttachmentManagement : attachmentManagementList){
                        if(comAttachmentManagement.getFileList().size()>0){
                            filenums=filenums+1;
                        }
                    }
                    if(management.getNeedNums()>filenums){
                        errorMsgList.add(management.getAttachmentName());
                    }
                }
            }
        });
        if(errorMsgList.size()>0){
            condition.setImageAttachmentsState(APP_FORM_STATE_ZERO);
            condition.setErrorMsg(errorMsgList.toString());
        }else{
            condition.setImageAttachmentsState(APP_FORM_STATE_ONE);
        }
        return condition;
    }

    /**
     * 人脸识别接口
     * @param condition
     * @return
     */
    @Override
    public IResponse signToFace(ApplyAppFaceCondition condition) {
        JSONObject json = new JSONObject();
        List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda().eq(ApplySignRelation::getCustId, condition.getCustId().toString()));
        if(signRelationList!=null && signRelationList.size()>0){
            AfsUser user = SecurityUtils.getUser();
            ApplySignRelation relation = signRelationList.get(0);
            // 见证人
            if(WITNESSES.equals(relation.getCustRole())){
                //根据客户id判断角色，拿到角色对应小类标识记录
                IResponse comAttach = applyAdminService.getUserFileByUserId(user.getId().toString());
                if("0000".equals(comAttach.getCode())){
                    Map map = (Map) comAttach.getData();
                    ComAttachmentFile attachmentFile = new ComAttachmentFile();
                    attachmentFile.setFileId((String) map.get("fileId"));
                    attachmentFile.setFileName((String) map.get("fileName"));
                    byte[] fileByte = attachmentFileService.downloadAttachmentFile(attachmentFile);
                    try {
                        if (fileByte.length > 0) {
                            String databaseImageContent = Base64.encodeBase64String(fileByte);
                            //被对比图片
                            json.put("databaseImageContent", databaseImageContent);
                        }
                    } catch (Exception e) {
                        log.error("文件下载失败:" + e.getMessage());
                    }
                }else{
                    return IResponse.fail("见证人脸对比图片不能为空");
                }
            }
            // 车商
            else if(CAR_DEALER.equals(relation.getCustRole())){
                ComAttachmentManagement comAttachmentManagement = comAttaManageService.getOne(Wrappers.<ComAttachmentManagement>query().lambda()
                        .eq(ComAttachmentManagement::getUniqueCode, CertTypePictureEnum.CONTRACT_INVOICE_ID_CARD_FRONT.getIndex())
                        .eq(ComAttachmentManagement::getBusiNode, BusiNodeEnum.LOAN_APPLY.getCode()));;
                if(comAttachmentManagement == null){
                    return IResponse.fail("客户信息不存在");
                }
                ApplyContractInfo contractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda().eq(ApplyContractInfo::getApplyNo, condition.getApplyNo()));
                if(contractInfo ==null){
                    //合同号赋值
                    return IResponse.fail("合同号不能为空");
                }
                List<ComAttachmentFile> comAttachmentFileList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getBusiNo, contractInfo.getContractNo())
                        .eq(ComAttachmentFile::getAttachmentCode,comAttachmentManagement.getId().toString()).orderByDesc(ComAttachmentFile::getCreateTime));

                if(comAttachmentFileList !=null && comAttachmentFileList.size()>0){
                    ComAttachmentFile attachmentFile = comAttachmentFileList.get(0);
                    byte[] fileByte = attachmentFileService.downloadAttachmentFile(attachmentFile);
                    try {
                        if (fileByte.length > 0) {
                            String databaseImageContent = Base64.encodeBase64String(fileByte);
                            //被对比图片
                            json.put("databaseImageContent", databaseImageContent);
                        }
                    } catch (Exception e) {
                        log.error("文件下载失败:" + e.getMessage());
                    }
                }else{
                    return IResponse.fail("人脸对比图片不能为空");
                }
            }else{
                ComAttachmentManagement comAttachmentManagement = getComAttachmentManagement(condition.getCustId());
                if(comAttachmentManagement == null){
                    return IResponse.fail("客户信息不存在");
                }
                List<ComAttachmentFile> comAttachmentFileList = attachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda()
                        .eq(ComAttachmentFile::getBusiNo, condition.getApplyNo())
                        .eq(ComAttachmentFile::getAttachmentCode,comAttachmentManagement.getId().toString()).orderByDesc(ComAttachmentFile::getCreateTime));

                if(comAttachmentFileList !=null && comAttachmentFileList.size()>0){
                    ComAttachmentFile attachmentFile = comAttachmentFileList.get(0);
                    byte[] fileByte = attachmentFileService.downloadAttachmentFile(attachmentFile);
                    try {
                        if (fileByte.length > 0) {
                            String databaseImageContent = Base64.encodeBase64String(fileByte);
                            //被对比图片
                            json.put("databaseImageContent", databaseImageContent);
                        }
                    } catch (Exception e) {
                        log.error("文件下载失败:" + e.getMessage());
                    }
                }else{
                    return IResponse.fail("人脸对比图片不能为空");
                }
            }
        }
        json.put("queryImagePackage", condition.getQueryImagePackage());
        json.put("databaseImageType","1");
        return IResponse.success(json);
    }

    /**
     * 人脸识别面签照上传
     * @param info
     * @return
     */
    @Override
    public IResponse faceToFaceSign(ApplyCustBaseInfo info,String queryImagePackage,ApplyAppFaceCondition condition) {
        JSONObject json = new JSONObject();
        Map<String, String> headers = new HashMap<>(3);
        headers.put("Authorization", this.getTempDir.getAuthorization());
        String fileName = AppEnum.ORDER_APPLY_FACE_PHOTO.getName();
        String file = AppEnum.ORDER_APPLY_FACE_PHOTO.getIndex();
        if(COMMON_BORROWER.equals(info.getCustRole())){
            file=AppEnum.ORDER_APPLY_BORROWER_FACE_PHOTO.getIndex();;
        }else if(GUARANTOR.equals(info.getCustRole())){
            file=AppEnum.ORDER_APPLY_GUARANTOR_FACE_PHOTO.getIndex();;
        }
        if(BusiNodeEnum.LOAN_APPLY.getCode().equals(condition.getBusiNode())){
            ApplyContractInfo contractInfo = applyContractInfoService.getOne(Wrappers.<ApplyContractInfo>query().lambda().eq(ApplyContractInfo::getApplyNo, info.getApplyNo()));
            if(contractInfo !=null){
                Map map = getTempDir.doUpload(queryImagePackage, fileName, headers);
                this.setImageStore(file, map, contractInfo.getContractNo(),condition);
            }else{
                IResponse.fail("合同信息不能为空！");
            }
        }else{
            Map map = getTempDir.doUpload(queryImagePackage, fileName, headers);
            this.setImageStore(file, map, info.getApplyNo(),condition);
        }
        return IResponse.success("上传成功");
    }


    /**
     * 保存MD5到file
     *
     * @param uniqueCode
     */
    public void setImageStore(String uniqueCode, Map<String, String> map, String params,ApplyAppFaceCondition condition) {
        //查询manage文件表内的数据
        ComAttachmentFile comAttachmentFile = new ComAttachmentFile();
        if(StrUtil.isBlank(condition.getBusiNode())){
            condition.setBusiNode(BusiNodeEnum.ORDER_APPLY.getCode());
        }
        ComAttachmentManagement comAttachmentManagement = this.managementMapper.selectOne(Wrappers.<ComAttachmentManagement>query().lambda()
                .eq(ComAttachmentManagement::getUniqueCode, uniqueCode)
                .eq(ComAttachmentManagement::getBusiNode,condition.getBusiNode()));

        //先查询
        ComAttachmentFile attachmentFile = this.comAttachmentFileService.getOne(Wrappers.<ComAttachmentFile>query().lambda()
                .eq(ComAttachmentFile::getBusiNo, params)
                .eq(StringUtil.isNotEmpty(comAttachmentManagement.getAttachmentName()),ComAttachmentFile::getAttachmentName,comAttachmentManagement.getAttachmentName()));
        if (ObjectUtil.isNotNull(attachmentFile)) {
            attachmentFile.setFileId(map.get("md5"));
            this.comAttachmentFileService.updateById(attachmentFile);
            log.info("{}", attachmentFile.getAttachmentName() + "更新成功");
        } else {
            if (ObjectUtil.isNotNull(comAttachmentManagement)) {
                comAttachmentFile.setBelongNo(params);
                comAttachmentFile.setBusiNo(params);
                comAttachmentFile.setAttachmentCode(String.valueOf(comAttachmentManagement.getId()));
                comAttachmentFile.setAttachmentName(comAttachmentManagement.getAttachmentName());
                comAttachmentFile.setFileStatus("standard");
                comAttachmentFile.setFileType("jpg");
                comAttachmentFile.setFileId(map.get("md5"));
                comAttachmentFile.setHistoryVersion(ApplyConstants.ZERO);
                comAttachmentFile.setIsElectronic(ApplyConstants.ZERO);
                comAttachmentFile.setFileName(comAttachmentManagement.getAttachmentName() + ".jpg");
                comAttachmentFile.setUploadTime(new Date());
                comAttachmentFile.setCreateBy(SecurityUtils.getUsername());
                comAttachmentFile.setFileSource("com_attachment_management");
                //存到file表
                this.comAttachmentFileService.save(comAttachmentFile);
                log.info("{}", comAttachmentManagement.getAttachmentName() + "上传成功");
            }
        }
    }
}
